<template>
  <div class="dashboard-container">
    <div class="app-container">
      <pagetool :show-before="true">
        <!-- <span slot="before">共166条记录</span> -->
        <template #before>
          <span>共{{ page.total }}条数据</span>
        </template>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPermission('add')" size="small" type="primary" @click="add">新增员工</el-button>
        </template>
      </pagetool>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <!-- 头像 -->
          <el-table-column label="头像" width="200">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" class="avatar" @click="showQRCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{row}">
              <el-switch :value="row.enableState===1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            hide-on-single-page
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <add-employee :show-dialog.sync="showDialog" @btnCancel="showDialog=false" @addEmployee="getEmployeeList" />
      <el-dialog title="二维码" :visible="isShowQRCode" @close="isShowQRCode=false">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 角色 -->
      <AssignRole ref="assignRole" :show-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
// import pagetool from '@/components/PageTools/index.vue'
import { getEmployeeList } from '@/api/employees'
import employeeEnum from '@/api/constant/employees'
import { formatDate } from '@/filters'
import { delEmployee } from '@/api/employees'
import AddEmployee from './component/add-employee.vue'
// import { export_json_to_excel } from '@/vendor/Export2Excel'
// 每次进来都进行导入, 如果用的频率不高, 就有点浪费
// 所以在下面按需引入

import QRCode from 'qrcode'
import AssignRole from './component/assign-role.vue'
export default {
  components: {
    AddEmployee,
    AssignRole
    // pagetool
  },
  data() {
    return {
      loading: false,
      list: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      showDialog: false,
      isShowQRCode: false,
      // 角色弹窗
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    // 获取员工列表数据
    this.getEmployeeList()
  },
  methods: {
    // 是否禁用按钮
    // checkPermission(btnName) {
    //   return this.$store.state.user.userInfo.roles.points.indexOf(btnName) !== -1
    // },
    // 角色
    async assignRole(id) {
      // 通过ref调用组件里的userDetialInfo方法，获取所有角色列表
      await this.$refs.assignRole.userDetialInfo(id)
      this.userId = id
      this.showRoleDialog = true
    },
    // 二维码 安装插件
    showQRCode(imgurl) {
      if (imgurl) {
        // 点击弹窗
        this.isShowQRCode = true
        this.$nextTick(() => {
          // 等弹窗渲染完, 创建二维码
          // 三个参数
          // 1. canvas dom
          // 2. 字符串
          // 3. 可选配置对象
          QRCode.toCanvas(this.$refs.myCanvas, imgurl, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.page)
      // console.log(res)
      this.list = rows.map(val => {
        return {
          ...val,
          enableState: val.enableState || 1 // 账户状态
        }
      })
      this.page.total = total
    },
    // 切换页码 改变数据
    changePage(newPage) {
      this.page.page = newPage
      // console.log(newPage)
      this.getEmployeeList()
    },
    // 枚举思想 大量数据需要判定 使用枚举循环判断
    // cellValue  格子数据
    // import employeeEnum from '@/api/constant/employees'
    formOfEmployment(row, column, cellValue, index) {
      const obj = employeeEnum.hireType.find(el => Number(el.id) === Number(cellValue))
      return obj ? obj.value : '未知'
    },
    async exportExcel() {
      // // 1. 获取所有员工
      // const { rows } = await getEmployeeList({
      //   page: 1,
      //   size: this.page.total
      // })
      // console.log(rows)
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.page.total
      })
      console.log('原数据', rows)
      // 中间进行数据转换
      // 就像之前的导入一样, 给个字典
      const dict = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 表头
      const header = Object.keys(dict)
      const data = rows.map(user => {
        // obj2arr函数将数组对象改为数组数组
        return this.obj2arr(user, dict)
      })

      // // 2. 生成 excel

      // 点击才引入，按需引入，提高性能
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      export_json_to_excel({
        header,
        data
      })
    },
    // 将user对象转为数组
    obj2arr(user, dict) {
      const newsArry = []
      // 中间这里写对象转数组逻辑
      for (const key in dict) {
        // 英文key
        const enkey = dict[key]
        const value = user[enkey]
        newsArry.push(value)

        // console.log('改变后', newsArry)
        if (enkey === 'formOfEmployment') {
          const obj = employeeEnum.hireType.find(el => el.id === value)
          newsArry.push(obj ? obj.value : '未知')
        } else if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          newsArry.push(formatDate(value))
        } else {
          return newsArry
        }
      }
    },
    async delEmployee(id) {
      await this.$confirm('确定删除？')
      await delEmployee(id)
      this.$message.success('删除成功')
      if (this.list.length === 1 && this.page.page > 1) {
        this.page.page--
      }
      this.getEmployeeList()
    },
    add() {
      this.showDialog = true
    }
    // btnCancel() {
    //   this.showDialog = false
    // }
  }
}
</script>

<style scoped>
.avatar {
  width: 180px;
  height: 140px;
  /* 如果一张图片强制设置了宽高
  但是又不想改变比例 */
  object-fit: cover
}
</style>
